import React, { useEffect, useRef, useState } from 'react'
import { Form, Input, Cascader, Button, message } from 'antd'
import { getDBAreaList, salesReturnAddress, salesReturnAddressAddOrEdit } from "@/api/afterSaleAddress"
import { ProFormTextArea } from "@ant-design/pro-components";
const { TextArea } = Input
import './style/style.scss';
import TheButton from "@/components/TheButton/index.jsx";
export default function FreightTemplate() {
  const formRef = useRef()
  const [options, setOptions] = useState([])
  const [addressData, setAddressData] = useState([])

  useEffect(() => {
    getData()
  }, [])
  const getData = async () => {
    let addressId = []
    await salesReturnAddress().then(async (res) => {
      if (res.code === 0 && res.data) {
        if ('addressProvinceId' in res.data && 'addressCityId' in res.data && 'addressDistrictId' in res.data) {
          addressId.push(Number(res.data.addressProvinceId), Number(res.data.addressCityId), Number(res.data.addressDistrictId))
          let arr = [
            {
              label: res.data.addressProvince,
              value: res.data.addressProvinceId
            },
            {
              label: res.data.addressCity,
              value: res.data.addressCityId
            },
            {
              label: res.data.addressDistrict,
              value: res.data.addressDistrictId
            },
          ]
          setAddressData(arr)
          await getAddressInfoData(addressId)
          formRef.current.setFieldsValue({ ...res.data, addressId })
        }
      } else {
        await getDBAreaList({ level: 1 }).then(res => {
          if (res.code === 0) {
            let arr = []
            arr = res.data.map((item) => {
              let params = {
                label: item.areaName,
                value: item.areaId,
                isLeaf: false
              }
              return params
            })
            setOptions(arr)
          }

        })
      }
    })

  }
  // 地址省市区数据请求
  const getAddressInfoData = async (addressId) => {
    await getDBAreaList({ level: 1 }).then(async (res) => {
      if (res.code === 0 && res.data) {
        let dbAreaData = res.data.map(item => {
          let params = {
            label: item.areaName,
            value: item.areaId,
            isLeaf: item.areaName === '台湾省'
          }
          if (item.areaId === addressId[0]) {
            getOrgTwoList(addressId[0], 2).then(res => {
              params.children = res
            })
          }
          return params
        })
        for (let i = 0; i < addressId.length; i++) {
          await getNextList(addressId[i - 1], i, dbAreaData)//获取下一层级的数据
        }
      }
    })
  }
  //根据父id获取下一层级数据回显在输入框上
  const getNextList = async (targetOption, index, dbAreaData) => {
    let obj = {
      level: index + 1
    }
    if (index !== 0) {
      obj.areaParentId = targetOption
    }
    let list = []
    await getDBAreaList(obj).then(res => {
      list = res.data.map((item) => {
        return {
          label: item.areaName,
          value: item.areaId,
          isLeaf: index + 1 == 3
        }
      })
    })
    //初始化时，this.options包含全部第一层级的数据
    dbAreaData.forEach((item) => {
      if (item.children) {
        item.children.forEach((ite) => {
          if (ite.value == targetOption) {
            ite.children = list
            return ite
          }
        })
      }
      if (item.value == targetOption) {//数据value值等于父id
        item.children = list
        return item
      }
    })
    setOptions([...dbAreaData])
  }
  // 实现动态加载数据
  const loadData = async (selectedOptions) => {
    const targetOption = selectedOptions[selectedOptions.length - 1] //父元素数据
    let areaParentId = targetOption.value //父级ID
    let index = selectedOptions.length + 1 //当前节点
    if (index <= 3) {
      let data = await getOrgTwoList(areaParentId, index)
      targetOption.children = data
    }
    setOptions([...options]);
  };
  // 获取市县接口数据
  const getOrgTwoList = async (areaParentId, index) => {
    if (areaParentId) {
      let arr = []
      await getDBAreaList({ level: index, areaParentId }).then(res => {
        if (res.code === 0) {
          res.data.forEach(item => {
            arr.push({
              label: item.areaName,
              value: item.areaId,
              isLeaf: index == 3 ? true : false//判断是否是叶子节点
            })
          })
        }
      })
      return arr;
    }
  }
  // 选择省市区
  const onChange = (e, searchOption) => {
    let arr = []
    arr = searchOption.map(item => {
      return {
        label: item.label,
        value: item.value,
      }
    })
    setAddressData(arr)
  }
  const onBlur = (e) => {
    let textarea = document.getElementById("myTextarea");
    if (e.target.value === '') {
      textarea.style.borderColor = "red";
    } else {
      textarea.style.borderColor = '#d9d9d9'
    }
  }
  const onFinish = async (value) => {
    let addressId = addressData.map(item => {
      return item.value
    })
    let addressName = addressData.map(item => {
      return item.label
    })
    let addressProvinceId = addressId[0] //省级id
    let addressCityId = addressId[1] // 市级id
    let addressDistrictId = addressId[2] //区级id
    let addressProvince = addressName[0] //省级名称
    let addressCity = addressName[1] // 市级名称
    let addressDistrict = addressName[2] //区级名称
    delete value.addressId
    let params = {
      ...value,
      addressProvinceId,
      addressCityId,
      addressDistrictId,
      addressProvince,
      addressCity,
      addressDistrict,
    }
    await salesReturnAddressAddOrEdit({ ...params }).then(async (res) => {
      if (res.code === 0) {
        message.success('保存成功')
      }
    })
  }
  return (
    <div className='warp-box' >
      <Form
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 4 }}
        ref={formRef}
        onFinish={onFinish}
      >
        <Form.Item label="收件人" name="addresseeName" rules={[{ required: true }]}>
          <Input maxLength={30} />
        </Form.Item>
        <Form.Item label="联系电话" name="addresseeMobile" rules={[{ required: true, pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '请输入11位手机号' }]} >
          <Input maxLength={11} />
        </Form.Item>
        <Form.Item label="省市县" name="addressId" rules={[{ required: true }]} >
          <Cascader placeholder="请选择省市县" options={options} loadData={loadData} onChange={onChange} />
        </Form.Item>
        <Form.Item label="详细地址" name="addressDetail" rules={[{ required: true }]}>
          <textarea id='myTextarea' maxLength={50} style={{ height: 150, width: '100%', borderColor: '#d9d9d9' }} onInput={onBlur}></textarea>
        </Form.Item>
        <Form.Item style={{ display: 'flex', justifyContent: 'center' }}>
          <TheButton haspermi={['afterSaleAddress:address:save']} htmlType="submit">保存</TheButton>
        </Form.Item>
      </Form>
    </div>
  )
}
